package Weclome;

import PersonalHomepage.AdminHomepage;
import PersonalHomepage.UserHomepage;
import Util.UiUtil;
import Util.UserDatabaseUtil;

import javax.swing.*;
import java.awt.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Timer;
import java.util.TimerTask;

public class Welcome {
    JFrame jf;
    public static JLabel background = new JLabel();
    JLabel welcome;
    boolean statue;
    String str = null;
    int count1 = 0;
    int count2 = 0;
    UiUtil ui = new UiUtil();
    void init() {
        jf = new JFrame("Welcome!");
        jf.setLayout(null);
        jf.setSize(1120, 628);
        jf.setResizable(false);

        background = UiUtil.setBackground(background);
        background.setBounds(0, 0, 1120, 628);

        welcome = new JLabel("You will enter the system in three seconds...");
        welcome.setBounds(340, 540, 500, 40);
        welcome.setFont(new Font("Times New Roman", Font.BOLD, 25));
        welcome.setForeground(Color.white);

        jf.add(welcome);
        jf.add(background);
    }

    public Welcome() {
        init();
        ui.setFrameCenter(jf);
        ui.setFrameImage(jf);

        isAdmin();

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if(count1 % 4 == 0)
                    str = "You will enter the system in five seconds...";
                else
                    str = str + ".";
                welcome.setText(str);
                if(count2 == 25)
                {
                    jf.dispose();
                    if (statue)
                        new AdminHomepage();
                    else
                        new UserHomepage();
                    timer.cancel();
                }
                count1++;
                count2++;
            }
        };
        timer.scheduleAtFixedRate(task,10,200);
        jf.setVisible(true);
    }

    private void isAdmin() {
        UserDatabaseUtil ud = new UserDatabaseUtil();
        try {
            Connection conn = ud.getConnection();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from userdata");
            while (rs.next()) {
                if (rs.getBoolean("isLogin") == true) {
                    statue = rs.getBoolean("isAdmin");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
